package controllers

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"ix-brow/models"
	"ix-brow/services"
)

// 用户列表响应体
type UserListResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// 管理页面 - 显示HTML页面
func AdminPage(c *gin.Context) {
	c.File("./static/admin.html")
}

func ProxyPage(c *gin.Context) {
	c.File("./static/admin.html")
}

// 获取用户列表API
func GetUserList(c *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	username := c.DefaultQuery("username", "")
	baseBrowserAccount := c.DefaultQuery("baseBrowserAccount", "")

	// 获取用户列表
	composites, total, err := models.GetUserList(page, pageSize, username, baseBrowserAccount)
	if err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "获取用户列表失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "成功",
		Data: map[string]interface{}{
			"total":    total,
			"list":     composites,
			"page":     page,
			"pageSize": pageSize,
		},
	})
}

// 获取用户浏览器组合视图API
func GetUserBrowserComposites(c *gin.Context) {
	// 获取用户浏览器组合视图
	composites, err := models.GetUserBrowserComposites()
	if err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "获取用户浏览器组合视图失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "成功",
		Data:    composites,
	})
}

// DeleteUser handles the deletion of a user account
func DeleteUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
		return
	}

	// Get user information before deletion to handle associated resources
	user, groups, browsers, err := models.GetUserByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
		return
	}

	log.Printf("开始删除用户 %s (ID: %s)，包含 %d 个分组和 %d 个浏览器",
		user.Username, user.ID, len(groups), len(browsers))

	// Get ixBrowser API client
	api := services.NewIxBrowserAPI()

	// 获取所有需要删除的外部分组ID和浏览器ID
	externalGroupIDs := models.GetExternalGroupIDs(groups)
	var externalBrowserIDs []int
	for _, browser := range browsers {
		if browser.ExternalBrowserID > 0 {
			externalBrowserIDs = append(externalBrowserIDs, browser.ExternalBrowserID)
		}
	}

	log.Printf("需要删除的外部资源: %d 个分组, %d 个浏览器", len(externalGroupIDs), len(externalBrowserIDs))

	// 先处理外部浏览器删除
	for _, browserID := range externalBrowserIDs {
		log.Printf("正在删除外部浏览器 (ID: %d)", browserID)
		if err := api.DeleteBrowser(browserID); err != nil {
			log.Printf("删除外部浏览器失败 (ID: %d): %v", browserID, err)
		} else {
			log.Printf("已删除外部浏览器 (ID: %d)", browserID)
		}
	}

	// 然后删除外部分组
	for _, groupID := range externalGroupIDs {
		log.Printf("正在删除外部分组 (ID: %d)", groupID)
		if err := api.DeleteGroup(groupID); err != nil {
			log.Printf("删除外部分组失败 (ID: %d): %v", groupID, err)
		} else {
			log.Printf("已删除外部分组 (ID: %d)", groupID)
		}
	}

	// 最后再尝试删除外部员工账号
	employeeInfo, err := api.FindEmployee(user.Username)
	if err != nil {
		log.Printf("查找员工信息失败 (用户: %s): %v", user.Username, err)
	} else if employeeInfo != nil {
		log.Printf("找到员工信息 (ID: %d, 名称: %s, 邮箱: %s)",
			employeeInfo.ID, employeeInfo.Name, employeeInfo.Email)

		// 删除员工账号
		err = api.DeleteEmployee(employeeInfo.ID)
		if err != nil {
			log.Printf("删除员工账号失败 (ID: %d): %v", employeeInfo.ID, err)
		} else {
			log.Printf("已成功删除员工账号 (ID: %d, 用户: %s)", employeeInfo.ID, user.Username)
		}
	} else {
		log.Printf("未找到员工信息 (用户: %s)，但已处理外部浏览器和分组资源", user.Username)
	}

	// 物理删除本地数据库中的用户及关联资源
	if err := models.PhysicallyDeleteUser(id); err != nil {
		log.Printf("物理删除用户失败 (ID: %s): %v", id, err)
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "删除用户失败: " + err.Error(),
		})
		return
	}

	log.Printf("已物理删除用户 (ID: %s, 用户名: %s)", id, user.Username)
	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "用户删除成功",
	})
}

// 禁用用户API
func DisableUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的用户ID",
		})
		return
	}

	if err := models.UpdateUserStatus(id, false); err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "禁用用户失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "用户禁用成功",
	})
}

// 启用用户API
func EnableUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的用户ID",
		})
		return
	}

	if err := models.UpdateUserStatus(id, true); err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "启用用户失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "用户启用成功",
	})
}

// 修改浏览器过期时间API
func UpdateBrowserExpiration(c *gin.Context) {
	idStr := c.Param("id")
	browserID, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的浏览器ID",
		})
		return
	}

	var req struct {
		ExpirationTime int64 `json:"expiration_time" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的请求参数",
		})
		return
	}

	expirationTime := time.Unix(req.ExpirationTime, 0)
	if expirationTime.Before(time.Now()) {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "过期时间不能小于当前时间",
		})
		return
	}

	if err := models.UpdateBrowserExpiration(browserID, expirationTime); err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "更新过期时间失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "过期时间更新成功",
	})
}

// 启用/禁用浏览器API
func ToggleBrowserStatus(c *gin.Context) {
	idStr := c.Param("id")
	browserID, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的浏览器ID",
		})
		return
	}

	var req struct {
		Active bool `json:"active" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的请求参数",
		})
		return
	}

	if err := models.UpdateBrowserStatus(browserID, req.Active); err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "更新浏览器状态失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: getMessage(req.Active),
	})
}

// Helper function to get the appropriate message based on active status
func getMessage(active bool) string {
	if active {
		return "浏览器启用成功"
	}
	return "浏览器禁用成功"
}

// 获取用户详情API
func GetUserDetail(c *gin.Context) {
	idStr := c.Param("id")
	id, err := uuid.Parse(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, UserListResponse{
			Code:    400,
			Message: "无效的用户ID",
		})
		return
	}

	// 获取用户和关联的分组、浏览器信息
	user, groups, browsers, err := models.GetUserByID(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, UserListResponse{
			Code:    500,
			Message: "获取用户详情失败: " + err.Error(),
		})
		return
	}

	// 获取ixBrowser API客户端
	api := services.NewIxBrowserAPI()

	// 尝试获取员工信息
	employee, _ := api.FindEmployee(user.Username)

	// 格式化分组信息
	var groupInfos []map[string]interface{}
	groupMap := make(map[uuid.UUID]map[string]interface{})

	for _, group := range groups {
		groupMap[group.ID] = map[string]interface{}{
			"id":         group.ID,
			"group_id":   group.GroupID,
			"group_name": group.GroupName,
			"active":     group.Active,
			"browsers":   []map[string]interface{}{},
		}
	}

	// 格式化浏览器信息并添加到相应的分组
	for _, browser := range browsers {
		if groupInfo, exists := groupMap[browser.GroupID]; exists {
			browsersList := groupInfo["browsers"].([]map[string]interface{})
			browsersList = append(browsersList, map[string]interface{}{
				"id":              browser.ID,
				"browser_name":    browser.BrowserName,
				"browser_type":    browser.BrowserType,
				"expiration_time": browser.ExpirationTime,
				"active":          browser.Active,
			})
			groupInfo["browsers"] = browsersList
		}
	}

	// 将分组信息转换为数组
	for _, groupInfo := range groupMap {
		groupInfos = append(groupInfos, groupInfo)
	}

	// 返回用户详情及关联信息
	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "成功",
		Data: map[string]interface{}{
			"user": map[string]interface{}{
				"id":       user.ID,
				"username": user.Username,
				"active":   user.Active,
			},
			"groups":   groupInfos,
			"employee": employee,
		},
	})
}

// 手动触发过期用户检查API
func TriggerExpiredUserCheck(c *gin.Context) {
	// 创建过期用户服务
	expiredUserService := services.NewExpiredUserService()

	// 在后台执行过期用户检查
	go expiredUserService.ProcessExpiredUsers()

	c.JSON(http.StatusOK, UserListResponse{
		Code:    200,
		Message: "过期用户检查已触发，正在后台执行",
	})
}
